package com.atguigu.exam;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 编写一个服务器和一个客户端

 1)服务器可以读取本地文件内容并能将内容发给请求的客户端
 2)再编写一个可以发请求到服务器,并能从服务器段获取文件内容的客户端
 * @author xbd
 * @create 2021-05-31 17:29
 */
public class ServerProjectTest {
    public void startServer(){
        ServerSocket ss = null;
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            ss = new ServerSocket(8899);
            socket = ss.accept();
            os = socket.getOutputStream();
            fis = new FileInputStream("a.jpg");
            byte[] bytes = new byte[20];
            int len;
            while ((len = fis.read(bytes)) != -1){
                os.write(bytes,0,len);
            }
//                os.write("老王我给你发了一个图片  你好好欣赏啊".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new ServerProjectTest().startServer();
    }
}
